import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Card, Form, Empty, Icon, Tooltip, Table, Spin, Badge, Divider } from 'antd';
import { useUpdateEffect } from '@umijs/hooks';
import classNames from 'classnames';
import ScrollBar from '@/components/ScrollBar';
import request from '@/utils/request';
import styles from '@/pages/FlowComp/less/stepList2.less';

function ObjFlowView(props) {
  const [flowNodeList, setFlowNodeList] = useState([]);
  const [planData, setPlanData] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [loading, setLoading] = useState(false);

  // 初始化
  useEffect(() => {
    if (props.objInstId != null) {
      request('pmc/pms/PmOrderFlowNodeController/queryListWithExec', {
        data: { objInstId: props.objInstId, objType: props.objType },
      }).then(res => {
        // res = {
        //   stackTrace: null,
        //   errCode: null,
        //   errMessage: null,
        //   data: [
        //     {
        //       extValues: {},
        //       flowNodeId: 30002,
        //       flowCode: 'ZTJ_VISIT_ACTIVE_CARD',
        //       flowId: 35002,
        //       flowNodeCode: 'CREATE_ORDER',
        //       flowNodeName: '创建订单',
        //       execId: 214007,
        //       execStatusCd: '1200',
        //       pmOrderFlowExecCOList: null,
        //     },
        //     {
        //       extValues: {},
        //       flowNodeId: 30003,
        //       flowCode: 'ZTJ_VISIT_ACTIVE_CARD',
        //       flowId: 35002,
        //       flowNodeCode: 'PARCEL_POST',
        //       flowNodeName: '寄送',
        //       execId: 214009,
        //       execStatusCd: '1100',
        //       pmOrderFlowExecCOList: null,
        //     },
        //     {
        //       extValues: {},
        //       flowNodeId: 30004,
        //       flowCode: 'ZTJ_VISIT_ACTIVE_CARD',
        //       flowId: 35002,
        //       flowNodeCode: 'ACTIVE_CARD',
        //       flowNodeName: '激活',
        //       execId: 217002,
        //       execStatusCd: '1000',
        //       pmOrderFlowExecCOList: null,
        //     },
        //     {
        //       extValues: {},
        //       flowNodeId: 30005,
        //       flowCode: 'ZTJ_VISIT_ACTIVE_CARD',
        //       flowId: 35002,
        //       flowNodeCode: 'ARCHIVE_ORDER',
        //       flowNodeName: '归档',
        //       execId: 224002,
        //       execStatusCd: '',
        //       pmOrderFlowExecCOList: null,
        //     },
        //   ],
        //   success: true,
        // };
        if (res && res.success) {
          setFlowNodeList(res.data);
        }
      });
    }
  }, [props.objInstId]);

  useUpdateEffect(() => {
    if (planData != null) {
      const tableList = [];
      planData.map(plan => {
        const table = (
          <div style={{ marginBottom: 20 }}>
            <div>
              <h4 style={{ display: 'inline' }}>方案名称：</h4>
              <span>{plan.planName}</span>
              &nbsp; &nbsp; &nbsp;
              <h4 style={{ display: 'inline' }}>事件名称：</h4>
              <span>{plan.eventName}</span>
            </div>
            <Table
              rowKey={record => record.ruleId}
              columns={columns}
              pagination={false}
              dataSource={plan.ruleExecList}
              bordered
            />
          </div>
        );
        tableList.push(table);
      });
      setTableList(tableList);
    } else {
      setTableList([]);
    }
  }, [planData]);

  const queryPlanData = item => {
    request('pmc/pms/PmOrderWorkController/flowExec/getRuleLog', {
      data: { execId: item.execId },
    }).then(res => {
      if (res && res.success) {
        if (res.data) {
          // eslint-disable-next-line array-callback-return
          res.data.map(item => {
            if (item.ruleExecList) {
              // eslint-disable-next-line array-callback-return
              item.ruleExecList.map(exec => {
                exec.children = exec.exeList;
              });
            }
          });
        }
        setPlanData(res.data);
      }
    });
  };

  const onChange = item => {
    queryPlanData(item);
  };

  const retryRulePlan = record => {
    // 找父节点数据
    const { planCode, objId, objType } = planData.filter(item => {
      return (
        item.ruleExecList !== null &&
        item.ruleExecList.filter(t => {
          return t.ruleId === record.ruleId && t.execResult === record.execResult;
        }).length > 0
      );
    })[0];

    setLoading(true);
    request('pmc/pms/rulePlan/retryRulePlan', {
      data: {
        planCode,
        objId,
        objType,
      },
    }).then(res => {
      setLoading(false);
      if (res && res.success) {
        setPlanData([...planData]);
      }
    });
  };

  const getStatusStyle = item => {
    if (item.execStatusCd === '1200') {
      return styles.finish;
    }
    if (item.execStatusCd === '1000') {
      return styles.process;
    }
    if (item.execStatusCd === '1100') {
      return styles.error;
    }
    return null;
  };

  const getIcon = (item, index) => {
    if (item.execStatusCd === '1200') {
      return <Icon type="check" />;
    }
    if (item.execStatusCd === '1100') {
      return <Icon type="close" />;
    }
    if (item.execStatusCd === '1000') {
      return <Icon type="environment" />;
    }
    return <span className={styles.stepsNumber}>{index + 1}</span>;
  };

  const getTitle = item => {
    if (item.execStatusCd === '1200') {
      return <span style={{ color: 'rgba(0, 0, 0, 0.65)' }}>{item.flowNodeName}</span>;
    }
    if (item.execStatusCd === '1000') {
      return <span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>{item.flowNodeName}</span>;
    }
    if (item.execStatusCd === '1100') {
      return <span style={{ color: 'rgba(245, 34, 45, 0.85)' }}>{item.flowNodeName}</span>;
    }
    return <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>{item.flowNodeName}</span>;
  };

  const columns = [
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      render: (text, record) => {
        return record.ruleRelName !== null ? `[${record.ruleRelName}]${text}` : text;
      },
    },
    {
      title: '规则编码',
      dataIndex: 'ruleCode',
    },
    {
      title: '状态',
      dataIndex: 'execResult',
      render: text => {
        return text === '-1' ? '未处理' : '已处理';
      },
    },
    {
      title: '处理结果',
      dataIndex: 'execResultName',
    },
    {
      title: '执行时间',
      dataIndex: 'execDate',
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      render: (text, record) => {
        return (
          <span style={{ display: record.execResult === '1' ? 'bolck' : 'none' }}>
            <a
              onClick={() => {
                retryRulePlan(record);
              }}
            >
              单步执行
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <Spin spinning={loading} tip="处理中，请稍候。。。">
      <Card title="流程导向" bordered={false} className="cute">
        <div className={classNames(styles.steps)} style={{ textAlign: 'left', marginBottom: 30 }}>
          <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 16 }}>
            <Badge status="success" text="处理完成" />
          </div>
          <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 16 }}>
            <Badge status="processing" text="正在处理" />
          </div>
          <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 16 }}>
            <Badge status="error" text="处理异常" />
          </div>
          <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 16 }}>
            <Badge status="default" text="未处理" />
          </div>
        </div>

        {flowNodeList.length > 0 ? (
          <ScrollBar autoHide autoHeight autoHeightMin="56px">
            <div className={classNames(styles.steps)}>
              {flowNodeList.map((item, index) => (
                <div className={styles.stepsItem}>
                  <div
                    className={classNames(styles.stepsItemIcon, [getStatusStyle(item)])}
                    onClick={() => onChange(item)}
                  >
                    {getIcon(item, index)}
                  </div>
                  <div className={styles.stepsItemContent} onClick={() => onChange(item)}>
                    <Tooltip placement="topLeft" title={item.flowNodeName}>
                      {getTitle(item)}
                    </Tooltip>
                  </div>
                  <div
                    className={classNames(styles.stepsItemLine, [
                      item.execStatusCd > '1000' ? styles.lineFish : null,
                    ])}
                  />
                </div>
              ))}
            </div>
          </ScrollBar>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无流程数据" />
        )}

        <h4 className="margin-z-lg">规则执行情况</h4>

        {/* <Divider className="small" /> */}

        {tableList.length ? (
          tableList.map(item => {
            return item;
          })
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
        )}
      </Card>
    </Spin>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(ObjFlowView));
